import { Card, Result, Button } from 'antd'
import { colors } from '@/desktop/styles'
import { useCorpDetail, type CorpDetail, type CorpInfo, type QywxAPIConfig } from '../logics/index'
import { APIInfo } from './api-info'
import { BaseInfo, BaseInfoExtra } from './base-info'
import { CallbackInfo } from './callback-info'

export function CorpDetailView({
  corpId,
  corps,
  apiConfigs,
  edit,
}: {
  corpId: string | null
  corps: CorpInfo[] | null
  apiConfigs: QywxAPIConfig[]
  edit: (detail: CorpDetail) => void
}) {
  const { detail, detailError, loadDetail } = useCorpDetail(corpId, corps, apiConfigs)

  if (detailError) {
    const reloadButton = <Button type="primary" size="small" onClick={loadDetail}>
      重新获取
    </Button>
    return <Result css={s.detailError} status="warning" title={detailError} extra={reloadButton} />
  }

  const detailLoading = corpId !== null && detail === null

  return <div css={s.detail}>
    <Card
      title="企业信息"
      extra={detail ? <BaseInfoExtra key={detail.corpId} detail={detail} edit={edit} /> : null}
      loading={detailLoading}
    >
      {detail ? (
        <BaseInfo key={detail.corpId} detail={detail} />
      ) : (
        <div css={s.empty}>请先选择或添加企业</div>
      )}
    </Card>

    <Card title="连通企微官方 API" loading={detailLoading} className={!detail ? 'empty-card' : ''}>
      {detail ? <APIInfo key={detail.corpId} detail={detail} /> : null}
    </Card>

    <Card
      title="接收企微后台事件回调"
      extra={<div css={s.desc}>实时获知联系人状态变化，如备注更新、好友删除</div>}
      loading={detailLoading}
      className={!detail ? 'empty-card' : ''}
    >
      {detail ? (
        <CallbackInfo key={detail.corpId} detail={detail} loadDetail={loadDetail} edit={edit} />
      ) : null}
    </Card>
  </div>
}

const s = {
  detailError: css`
    .ant-result-title {
      font-size: 16px;
    }
  `,
  empty: css`
    color: #aaa;
  `,
  detail: css`
    .ant-card {
      margin-top: 20px;
    }
    .ant-card.empty-card {
      .ant-card-head {
        border-bottom: none;
      }
      .ant-card-body {
        display: none;
      }
    }
    .row {
      display: flex;
      &:not(:last-child) {
        margin-bottom: 14px;
      }
      label {
        color: ${colors.gray};
        margin-right: 1em;
        text-align: right;
        width: 8.1em;
      }
      span + a {
        margin-left: 1.2em;
      }
    }
  `,
  desc: css`
    color: #999;
    font-size: 13px;
  `,
}
